package com.hitqz.robot.biz.config;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;


/**
 * @author xupkun
 * @date 2024/6/4
 */
@Configuration
public class ClientCorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    @Bean
    public FilterRegistrationBean<IFrameAllowFilter> iframeAllowFilter() {
        FilterRegistrationBean<IFrameAllowFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new IFrameAllowFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("iframeAllowFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    public static class IFrameAllowFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            // 允许所有网站通过iframe嵌入当前页面
            httpResponse.setHeader("X-Frame-Options", "");

            // 使用Content-Security-Policy允许所有源嵌入iframe
            httpResponse.setHeader("Content-Security-Policy", "frame-ancestors *;");

            // 添加额外的跨域相关头部
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            httpResponse.setHeader("Access-Control-Allow-Headers", "*");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");

            chain.doFilter(request, response);
        }
    }
}
